package com.gx.smart.building.ui.photo.fragment;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.ToastUtils;
import com.gx.smart.building.ui.photo.model.SaveImage;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnLvItemClickListener;
import com.orhanobut.logger.Logger;
import com.previewlibrary.view.BasePhotoFragment;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaosy
 * @create 2020/7/30
 * @Describe
 **/
public class PhotoPreviewFragment extends BasePhotoFragment implements View.OnLongClickListener {
    public static final int REQUEST_CODE = 0x10;
    private List<String> permissionsToRequire = new ArrayList<>();
    private List<SaveImage> items = new ArrayList<>();
    private boolean permissionFlag = true;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequire.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequire.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        imageView.setOnLongClickListener(this);
        SaveImage image = new SaveImage("保存图片到手机相册");
        items.add(image);
    }

    @Override
    public boolean onLongClick(View v) {
        new CircleDialog.Builder()
                .setItems(items, new OnLvItemClickListener() {

                    @Override
                    public boolean onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (permissionsToRequire.isEmpty()) {
                            saveImage();
                            Logger.d("saveImage");
                        } else {
                            Logger.d("requestPermissions");
                            ActivityCompat.requestPermissions(getActivity(), permissionsToRequire.toArray(new String[permissionsToRequire.size()]), REQUEST_CODE);
                        }
                        return true;
                    }
                })
                .setNegative("取消", null)
                .show(getActivity().getSupportFragmentManager());
        return false;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Logger.d("onRequestPermissionsResult");
        if (requestCode == REQUEST_CODE) {
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    ToastUtils.showLong("你允许获取所有的权限");
                    getActivity().finish();
                    permissionFlag = false;
                }
            }
            if (permissionFlag) {
                saveImage();
            }
        }
    }

    private void saveImage() {
        Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        String displayName = System.currentTimeMillis() + ".jpg";
        String mimeType = "image/jpeg";
        Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;
        addBitmapToAlbum(bitmap, displayName, mimeType, compressFormat, getContext().getContentResolver());
    }

    public void addBitmapToAlbum(Bitmap bitmap, String displayName, String mimeType, Bitmap.CompressFormat compressFormat, ContentResolver contentResolver) {
        Logger.d("addBitmapToAlbum");
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName);
        values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
        } else {
            values.put(MediaStore.MediaColumns.DATA, Environment.getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_DCIM + "/" + displayName);
        }
        Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        if (uri != null) {
            try {
                OutputStream outputStream = contentResolver.openOutputStream(uri);
                if (outputStream != null) {
                    bitmap.compress(compressFormat, 100, outputStream);
                    outputStream.flush();
                    outputStream.close();
                    ToastUtils.showLong("保存图片成功");
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Logger.e(e, "addBitmapToAlbum");
            } catch (IOException e) {
                e.printStackTrace();
                Logger.e(e, "addBitmapToAlbum");
            }

        }
    }
}
